var baseInfo = null;
var products = null;
var vips = null;
var vipsdetails = null;

var changeVipTab = function(mobile){
	 //alert(mobile);
	
	//当点击从viplist到vipdetail时，先把两个都隐藏，只会显示动态条。数据加载完成时，会显示详情信息。如果加载失败，则提示失败，不显示其他信息。
	 var $vip =$('#ul_vip');
	 var $vipdetails =$('#ul_vipdetails');
	 
	 if(!$vip.hasClass("am-hide")){
	  		$vip.addClass("am-hide");
	 }
	 
	 if(!$vipdetails.hasClass("am-hide")){
		 $vipdetails.addClass("am-hide");
	 }
	  	

	 
	 //if(vipsdetails==null){
		 loadVipDetails(mobile);
	 //}

};

var buildVipDetailsParams =function(mobile){
	 var params ={"BODY":{"UNIT_ID":getParamValue("grpId"),"PHONE_NO": mobile,"SERVICE_NO":""}};  //getParamValue("EmpCode")
    return params;
}

var showVipDetails = function(data){
	$("#vip_name").html(data.name);	
	$("#vip_mgr_empcode").html($("#mgrEmpCode").html());	
	$("#vip_mgrname").html($("#mgrName").html());	
	$("#vip_member_type").html(data.contract_no);	
	$("#vip_depart").html(data.department);	
	$("#vip_sex").html(data.sex);	
	$("#vip_addr").html(data.address);	
	$("#vip_pos").html(data.duty);	
	$("#vip_b_mgr").html(data.service_no);	
	$("#vip_ent_mgr").html(data.service_no);	
	$("#vip_city").html(data.region_name);	
	$("#vip_birthday").html(data.birthday);	
	$("#vip_hobby").html(data.love);	
	$("#vip_duty").html(data.duty);	
	$("#vip_mobile").html(data.phone_no);	
	$("#vip_isvip").html(data.is_vip);	
	$("#vip_card_no").html(data.card_no);	
	
	
	$("#vip_is_vip_mgr").html(data.isVipManage);	
	$("#vip_is_guochang").html(data.isguochang);	
	$("#vip_is_guoman").html(data.isguoman);	
	$("#vip_is_redlist").html(data.isredlist);	
	$("#vip_is_bind").html(data.isbind);	
	
	$("#vip_valid_time").html(data.valid_time);	
	$("#vip_owe_money").html(data.owe_money);
	
	 var $vipdetails =$('#ul_vipdetails');
	 if($vipdetails.hasClass("am-hide")){
	       $vipdetails.removeClass("am-hide");
     }	
	
};
var loadVipDetails = function(mobile){
    showLoadingBar($('#loadingbar'),true);
  	console.log("userid:"+getParamValue("userId"));
  	params = buildVipDetailsParams(mobile);
 	$.ajax({
	    type: "post",
	    contentType: "application/json",
	    data: JSON.stringify(params),
	    url: Constants.rpcCrmHost+"sGrpImpMInfo?token="+getToken(),
	    dataType: "json",
	    async: true,
	    headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
	    	showLoadingBar($('#loadingbar'),false);
	    	console.info(data);
	        console.info(data.ROOT);
	        if(data.ROOT.RETURN_CODE!=0){
	        	alert("调用接口返回失败,code:"+data.ROOT.RETURN_CODE+", msg:"+data.ROOT.RETURN_MSG);
	        	return;
	        }
	        vipsdetails = data.ROOT.OUT_DATA;
	        showVipDetails(vipsdetails);
	    },
	    error : function(textStatus) {
	    	showLoadingBar($('#loadingbar'),false);
	        alert("获取基本信息失败！");
	        console.info("request error:");
	    }
	  });
};


var initVipTab = function(){
	 var $vip =$('#ul_vip');
	 var $vipdetails =$('#ul_vipdetails');
	 
	  	if(!$vipdetails.hasClass("am-hide")){
	  		$vipdetails.addClass("am-hide");
	  	}
	  	
	    if($vip.hasClass("am-hide")){
	    	$vip.removeClass("am-hide");
		}		
}

var showVipsContent = function(){
	$ul_vips = $("#ul_vips");
	if($ul_vips.hasClass("am-hide")){
		$ul_vips.removeClass("am-hide");
	}
}

var hideVipsContent=function(){
	$ul_vips = $("#ul_vips");
	if(!$ul_vips.hasClass("am-hide")){
		$ul_vips.addClass("am-hide");
	}
}


var showVips = function(data){
	var $tpl = $('#amz-tpl');
    var source = $tpl.text();
    var template = Handlebars.compile(source);
    var myData = {
    	list: data,
    	"error":"没有集团信息"
    };
    
    var html = template(myData);
    $tpl.before(html);
    showVipsContent();
    
};
var buildVipsParams =function(){
    var params ={"BODY":{"UNIT_ID":getParamValue("grpId"),"SERVICE_NO":getParamValue("EmpCode")}};
    return params;
}
var loadVips = function(){
	hideErrorMsg($("#error_msg_vips"));
    showLoadingBar($('#loadingbar'),true);
  	console.log("userid:"+getParamValue("userId"));
  	params = buildVipsParams();
 	$.ajax({
	    type: "post",
	    contentType: "application/json",
	    data: JSON.stringify(params),
	    url: Constants.rpcCrmHost+"sGrpImpMbr?token="+getToken(),
	    dataType: "json",
	    async: true,
	    headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
	    	showLoadingBar($('#loadingbar'),false);
	    	console.info("data = "+data);
	        console.info(data.ROOT);
	        if(data.ROOT.RETURN_CODE!=0){
	        	hideVipsContent();
	        	showErrorMsg($("#error_msg_vips"),data.ROOT.RETURN_MSG);
	        	console.log("调用接口返回失败,code:"+data.ROOT.RETURN_CODE+", msg:"+data.ROOT.RETURN_MSG);
	        	return;
	        }

	        vips = data.ROOT.OUT_DATA.USER_INFO;
	        showVips(vips);
	    },
	    error : function(textStatus) {
	    	hideVipsContent();
	    	showLoadingBar($('#loadingbar'),false);
	    	showErrorMsg($("#error_msg_vips"),"获取重要成员信息失败！接口没有返回");
	        console.info("request error:");
	    }
	  });
};

var buildProductsParams =function(){
    var params ={"BODY":{"WORN_SERV_CODE":"sGrpProdInfo","COMMON_INFO":{"PROVINCE_GROUP":"10008"},"UNIT_ID":getParamValue("grpId"),"PHONE_NO": "15982618866","LOGIN_NO":getEmpCode()}};  
    return params;
}

var showProductsContent = function(){
	$ul_products = $("#ul_products");
	if($ul_products.hasClass("am-hide")){
		$ul_products.removeClass("am-hide");
	}
}

var hideProductsContent=function(){
	$ul_products = $("#ul_products");
	if(!$ul_products.hasClass("am-hide")){
		$ul_products.addClass("am-hide");
	}
}


var getDate = function(time){
	var date=time.substring(0,4)+"-"+time.substring(4,6)+"-"+time.substring(6,8);
	return date;
}

var showProducts = function(data){
	showProductsContent();
	var product = (data instanceof Array)?data[0]:data;
	$("#product_type").html(product.PRODUCT_TYPE);
	$("#product_name").html(product.PRODUCT_NAME);
	$("#group_product_id").html(product.GRP_PROD_ID);
	$("#product_mobile").html(product.FEE_PHONENO==0?"无":product.FEE_PHONENO);
	$("#group_virtual_number").html(product.GRP_VIR_NO);
	$("#group_product_status").html(product.GRP_PROD_STATUS);
	var open_date = product.OPEN_TIME;
	$("#open_date").html(getDate(open_date));
	$("#update_date").html(getDate(product.STATUS_UPD_TIME));
	$("#sms_port").html(product.SMS_PORT);

};

var loadProducts = function(){
	hideErrorMsg($("#error_msg_products"));
    showLoadingBar($('#loadingbar'),true);
  	console.log("userid:"+getParamValue("userId"));
  	params = buildProductsParams();
 	$.ajax({
	    type: "post",
	    contentType: "application/json",
	    data: JSON.stringify(params),
	    url: Constants.rpcCrmHost+"sUserOrdQry?token="+getToken(),
	    dataType: "json",
	    async: true,
	    headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
	    	showLoadingBar($('#loadingbar'),false);
	    	console.log("data = "+data);
	        console.info(data);
	        if(data.ROOT.RETURN_CODE!=0){
	        	hideProductsContent();
	        	showErrorMsg($("#error_msg_products"),data.ROOT.RETURN_MSG);
	        	console.log("获取RPC基本信息接口返回失败！code:"+data.ROOT.RETURN_CODE);
	        	return;
	        }
	       
	        products = data.ROOT.OUT_DATA.GRP_PROD_LIST;
	        if(products){
	        	 showProducts(products);
	        }else{
	        	 hideProductsContent();
	        	 showErrorMsg($("#error_msg_products"),"没有产品信息");
	        }
	    },
	    error : function(textStatus) {
	    	hideProductsContent();
	    	showLoadingBar($('#loadingbar'),false);
	    	showErrorMsg($("#error_msg_products"),"获取产品列表信息失败！服务器没有返回。");
	        console.info("request error:"+data);
	    }
	  });
};



var  showBaseInfo =function(data){
	
	showBaseContent();
	
	//放在这里加载，实现数据的一体加载
    var mgrName=decodeURI(getParamValue("mgrName"));
    var mgrEmpCode=getParamValue("mgrEmpCode");
    var grpName=decodeURI(getParamValue("grpName"));
    $("#mgrName").html(mgrName);
    $("#mgrEmpCode").html(mgrEmpCode);
    $("#grpName").html(grpName);
    
    
    
    
	var memberCount = getValue(data.memberCount);
	if(memberCount==null){
		$("#memberCount").html("0人");	
	}else{
		$("#memberCount").html(memberCount+"人");	
	}
	
    var income = getValue(data.income);
	if(income==null){
		$("#income").html("0元");	
	}else{
		$("#income").html(income+"元");	
	}
	var entType=getValue(data.entType);
	if(entType==null){
		$("#entType").html("无");	
	}else{
		$("#entType").html(entType);	
	}
	
	var entVNetScale=getValue(data.entVNetScale);
	if(entVNetScale==null){
		$("#entVNetScale").html("0人");	
	}else{
		$("#entVNetScale").html(entVNetScale+"人");	
	}
	
	var consume=getValue(data.consume);
	if(consume==null){
		$("#consume").html("0元");	
	}else{
		$("#consume").html(parseInt(consume)+"元");	
	}
	
	var netOutRate = getValue(data.netOutRate);
	if(netOutRate==null){
		$("#netOutRate").html("无");	
	}else{
		$("#netOutRate").html((parseFloat(netOutRate)*100).toFixed(2)+"%");	
	}

	var doubleTerminalState=getValue(data.doubleTerminalState);
	if(doubleTerminalState==null){
		$("#doubleTerminalState").html("0人");	
	}else{
		$("#doubleTerminalState").html(doubleTerminalState+"人");	
	}
	
	var userScope = getValue(data.userScope);
	if(userScope==null){
		$("#userScope").html("0人");	
	}else{
		$("#userScope").html(userScope+"人");	
	}
	
};

var getValue=function(value){
	if(value instanceof Object){
		return null;
	}
	return value;
}

var buildBaseInfoParams =function(){
    var params ={"token":getParamValue("token"),"staffNo":getParamValue("EmpCode"),"passUrl":"grpNo="+getParamValue("grpId")};
    return params;
}
var loadBaseInfo = function(){
	 hideErrorMsg($("#error_msg_baseinfo"));
	    showLoadingBar($('#loadingbar'),true);
	  	console.log("userid:"+getParamValue("userId"));
	  	params = buildBaseInfoParams();
	 	$.ajax({
		    type: "post",
		    contentType: "application/json",
		    data: JSON.stringify(params),
		    url: Constants.rpcEsopHost+"queryGrouInfoDetail",
		    dataType: "json",
		    async: true,
		    headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
		    	showLoadingBar($('#loadingbar'),false);
		    	console.log("data = "+data);
		        console.info(data.return);
		        if(data.rtnCode!=1000){
		        	hideBaseContent();
		        	showErrorMsg($("#error_msg_baseinfo"),data.rtnMsg);
		        	console.log("获取RPC基本信息接口返回失败！code:"+data.rtnCode);
		        	return;
		        }
		        if(data.return.resultCode!="00"){
		        	hideBaseContent();
		        	showErrorMsg($("#error_msg_baseinfo"),data.return.resultDesc);
		        	console.log("获取基本信息接口返回失败！code:"+data.return.resultCode);
		        	return;
		        }
		        baseInfo = data.return.groupInfo;
		        showBaseInfo(data.return.groupInfo);
		    },
		    error : function(textStatus) {
		    	hideBaseContent();
		    	showLoadingBar($('#loadingbar'),false);
		    	showErrorMsg($("#error_msg_baseinfo"),"获取基本信息失败！服务器没有返回。");
		        console.info("request error:");
		    }
		  });
};

var showBaseContent = function(){
	$baseInfo = $("#ul_baseinfo");
	if($baseInfo.hasClass("am-hide")){
		$baseInfo.removeClass("am-hide");
	}
}

var hideBaseContent=function(){
	$baseInfo = $("#ul_baseinfo");
	if(!$baseInfo.hasClass("am-hide")){
		$baseInfo.addClass("am-hide");
	}
}

var showErrorMsg = function(errMsgId,msg){
	if(msg==null){
		msg="接口返回失败，错误信息为空";
	}
	errMsgId.html(msg);
	if(errMsgId.hasClass("am-hide")){
		errMsgId.removeClass("am-hide");
	}
};

var hideErrorMsg = function(errMsgId){
	if(!errMsgId.hasClass("am-hide")){
		errMsgId.addClass("am-hide");
	}
};

$(function(){
	loadBaseInfo();
	 
    

    $('#mytabs').find('a').on('click', function(e) {
		console.log('[%s] 选项卡打开了', $(this).text());
		//基本信息已经加载，切换的时候，统一都不加载
		if( $(this).text()=="基本信息"){
			//获取失败后，点击tab可重新获取
			if(baseInfo==null){
				loadBaseInfo();
			}
		}
		//其余两个tab，如果发现没有数据，则加载。如有数据，则不加载。
		if($(this).text()=="产品列表"){
			if(products==null){
				console.log("to load products");
				loadProducts();
			}	
		}
		else if($(this).text()=="重要成员"){
			initVipTab();
			if(vips==null){
				console.log("to load vips");
				loadVips();
			}	
		}

    })
	
});